package com.chinatechstar.component.commons.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * @author Rei
 * @date 2021/7/17
 */
public class SerializerBigDecimal extends JsonSerializer<BigDecimal> {
    /**
     * 出参保留两位小数
     *
     * @param value       值
     * @param gen         JsonGenerator
     * @param serializers SerializerProvider
     * @throws IOException IOException
     */
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (Objects.isNull(value)) {
            gen.writeNull();
        } else {
            gen.writeNumber(value.setScale(2, RoundingMode.HALF_UP));
        }
    }

}
